package com.zznzzn.androidshixun0826;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.PersistableBundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.io.ByteArrayOutputStream;
import java.io.File;

public class ContactInfoActivity extends AppCompatActivity {

    private ImageView info_img;
    private EditText info_name, info_phone, info_address;
    private Button info_yes, info_no, info_del;
    private View.OnClickListener infobtnlinstener;
    private TextWatcher infowatcher;
    private ContactLib cl;
    private Contact ct;
    private int id, position,old_position,cid;
    private TextView name_sms,phone_call;
    private File moutPutFile;
    private Bitmap mbm;


    private final int REQUEST_CODE_TAKE_PHOTO = 101;
    private final int REQUEST_CODE_CLIP_PHOTO = 102;
    private final int REQUEST_CODE_LOAD_PHOTO = 103;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact_info);
        setTitle("修改信息");

        info_img = findViewById(R.id.info_img);
        info_name = findViewById(R.id.info_name);
        info_phone = findViewById(R.id.info_phone);
        info_address = findViewById(R.id.info_address);
        info_yes = findViewById(R.id.info_yes);
        info_no = findViewById(R.id.info_no);
        info_del = findViewById(R.id.info_del);
        name_sms = findViewById(R.id.name_sms);
        phone_call = findViewById(R.id.phone_call);

        info_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 单击 进入拍照页面
                if (hasCam()){
                    takePhoto();
                }else {
                    return;
                }
            }
        });

        info_img.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                // 长摁 打开相册intent
                Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent,REQUEST_CODE_LOAD_PHOTO);
                info_yes.setEnabled(true);
                return true;
            }
        });


        infobtnlinstener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.info_yes:
                        submit();
                        break;
                    case R.id.info_no:
                        cancel();
                        break;
                    case R.id.info_del:
                        delete();
                        break;
                    default:
                        break;
                }
            }
        };

        info_yes.setOnClickListener(infobtnlinstener);
        info_no.setOnClickListener(infobtnlinstener);
        info_del.setOnClickListener(infobtnlinstener);


        infowatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                info_yes.setEnabled(true);
            }
        };

        info_name.addTextChangedListener(infowatcher);
        info_phone.addTextChangedListener(infowatcher);
        info_address.addTextChangedListener(infowatcher);


        cl = ContactLib.get_lib(this);

        ct = (Contact) getIntent().getSerializableExtra("contact");
        old_position = getIntent().getIntExtra("index",-1);
        if (old_position == -1){
            Toast.makeText(this,":error",Toast.LENGTH_SHORT).show();
            finish();
        }
//
        if (savedInstanceState != null) {
            ct = (Contact) savedInstanceState.getSerializable("contact");
            info_yes.setEnabled(false);
        }

        init();


    }


    public void init() {

        cid = ct.getId(); //保存数据库记录中的id
        mbm = BitmapFactory.decodeByteArray(ct.getPhoto(),0,ct.getPhoto().length);
        info_img.setImageBitmap(mbm);

        info_name.setText(ct.getName());
        info_phone.setText(ct.getPhone());
        info_address.setText(ct.getAddress());

        info_yes.setEnabled(false);

        info_name.setClickable(true);
        info_phone.setClickable(true);

        name_sms.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("--sms","clicked");
                Intent sms = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:" + ct.getPhone()));
                sms.putExtra("sms", "Hello World!");
                if (ActivityCompat.checkSelfPermission(ContactInfoActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    Toast.makeText(ContactInfoActivity.this, "无短信权限", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(sms);
            }
        });

        phone_call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("--call","clicked");
                Intent call = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + ct.getPhone()));
                if (ActivityCompat.checkSelfPermission(ContactInfoActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    Toast.makeText(ContactInfoActivity.this, "无电话权限", Toast.LENGTH_SHORT).show();
                    return;
                }
                startActivity(call);
            }
        });

    }

    public void delete(){
        AlertDialog dialog = new AlertDialog.Builder(this).create();
        dialog.setTitle("FBI WARNING!");
        dialog.setMessage("Are you sure to delete?");
        dialog.setIcon(android.R.drawable.ic_dialog_alert);
        DialogInterface.OnClickListener dialogListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (which == DialogInterface.BUTTON_POSITIVE) {
                    cl.delContact(cl.getContact(old_position));
                    setResult(201);
                    finish();
                }else{
                    dialog.dismiss();
                }
            }
        };
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE,"取消",dialogListener);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE,"确定",dialogListener);
        dialog.show();

    }

    private byte[] bmtobt(Bitmap bm){
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG,100,bos);
        return bos.toByteArray();
    }

    public void submit(){
        String name = info_name.getText().toString();
        String phone = info_phone.getText().toString();
        String address = info_address.getText().toString();

        Contact xiaohong = new Contact(cid,name,phone,address,bmtobt(mbm));
        cl.setContact(xiaohong);
        setResult(200);
        finish();

    }

    public void cancel(){
        setResult(302);
        finish();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {

        outState.putSerializable("contact",ct);
        Log.d("==contact=======",ct.toString());
        super.onSaveInstanceState(outState);
    }


    private boolean hasCam(){
        PackageManager pm = getPackageManager();
        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA) && !pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT)){
            Toast.makeText(this,"no camara found",Toast.LENGTH_SHORT).show();
            return false;
        }else{
            return true;
        }
    }

    private void takePhoto(){
        //调用系统拍照 intent

        String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
        moutPutFile = new File(sdPath,System.currentTimeMillis()+".tmp");
        Uri uri = Uri.fromFile(moutPutFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
        startActivityForResult(intent,REQUEST_CODE_TAKE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_TAKE_PHOTO){
            onTakePhotoFinished(resultCode,data);
        }else if(requestCode == REQUEST_CODE_CLIP_PHOTO){
            onClipPhotoFinished(resultCode,data);
        }else if (requestCode == REQUEST_CODE_LOAD_PHOTO){
            onSelectPhotoFinished(resultCode,data);
        }
    }

    private void onSelectPhotoFinished(int resultCode, Intent data) {
        // 定位从相册中选取到的图片
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"select photo canceled",Toast.LENGTH_SHORT).show();
        }else if (resultCode == RESULT_OK && data != null){
            Uri selected = data.getData();
            Log.d("===selected==", String.valueOf(selected));
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selected,filePathColumn,null,null,null);
            cursor.moveToFirst();
            int index = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(index);
            cursor.close();

            moutPutFile = new File(picturePath);
            clipPhoto(selected);
        }
    }

    private void onClipPhotoFinished(int resultCode, Intent data) {
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"clip photo canceled",Toast.LENGTH_SHORT).show();
        }else if(resultCode != RESULT_OK){
            Toast.makeText(this,"clip photo failed",Toast.LENGTH_SHORT).show();
        }else {
            //显示裁切后图片
            mbm = BitmapFactory.decodeFile(moutPutFile.getAbsolutePath()+"tmp");
            info_img.setImageBitmap(mbm);
        }
    }

    private void onTakePhotoFinished(int resultCode, Intent data) {
        // 拍照成功后
        if (resultCode == RESULT_CANCELED){
            Toast.makeText(this,"take photo canceled",Toast.LENGTH_SHORT).show();
        }else if (resultCode != RESULT_OK){
            Toast.makeText(this,"take photo failed",Toast.LENGTH_SHORT).show();
        }else{
            clipPhoto(Uri.fromFile(moutPutFile));
        }
    }

    private void clipPhoto(Uri uri) {
        //调用系统自带的裁剪工具
        Log.d("====from uri==",uri.toString());

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        intent.putExtra("outputX",300);
        intent.putExtra("outputY",300);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(moutPutFile.getAbsoluteFile() + "tmp")));
        startActivityForResult(intent,REQUEST_CODE_CLIP_PHOTO);
    }
}
